package thread;

//****volatile 内存可见性->内存嗅探技术
//volatile与synchronized的区别

public class Test18_volatile_1 {
    public static void main(String[] args) throws InterruptedException {
        Task task = new Task();
        Thread t = new Thread(task,"线程1");

        Thread t1 = new Thread(()->{
            try {
                Thread.sleep(1000);
                System.out.println("开始通知线程停止");
                task.stop = true;//修改stop变量值，在t运行1s后，关闭t线程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"线程2");
        t.start();
        t1.start();
        Thread.sleep(1000);
    }
}

class Task implements Runnable{
    volatile boolean stop = false;//类的一个属性，内存可见性
    int i =0;
    @Override
    public void run() {
        long s = System.currentTimeMillis();
        while (!stop){
            i++;
        }
        System.out.println("线程退出"+(System.currentTimeMillis()-s));
    }
}
